from flask import (
    Blueprint,
    request,
    g,
    jsonify
)
from datetime import datetime, timedelta, date
from .decorators import login_required
from utils import restful, api_util, scan_pay, common_util
from apps.common.models import *
from decimal import Decimal
from .models import *
from sqlalchemy import or_


bp = Blueprint("api2.0", __name__, url_prefix="/api/v2.0")


@bp.route('/test/')
def test():
    return '测试'


@bp.route('/withdraw_scan_pay/', methods=['POST'])
@login_required
def withdraw_scan_pay():
    time_required = api_util.trade_time_required(4)
    if time_required is False:
        return restful.params_error(message='当前时间未开放')
    try:
        price = request.form.get('price')
        w_type = request.form.get('w_type')
        user_url = request.form.get('user_url')
        pay_type = request.form.get('pay_type')
        if not all([user_url, price, pay_type, w_type]):
            return restful.params_error(message='参数错误')
        pay_type = int(pay_type)
        w_type = int(w_type)
        price = Decimal(price)
        if price < 0:
            return restful.params_error(message='金额不合法')
        if price < 300:
            return restful.params_error(message='提现需300元起, 100的倍数！')
        if price % 100 != 0:
            return restful.params_error(message='提现金额需为100的倍数')
        poundage = price * Decimal('1.05')
        if poundage > g.user.income_s:
            return restful.params_error(message='资产不足')
        g.user.income_s -= poundage
        # if w_type == 1:
        #     if poundage > g.user.income:
        #         return restful.params_error(message='资产不足')
        #     g.user.income -= poundage
        # else:
        #     if poundage > g.user.income_r:
        #         return restful.params_error(message='资产不足')
        #     g.user.income_r -= poundage
        trade_no = common_util.trade_no_time()
        result = scan_pay.scan_pay_api(
            order_id=trade_no, pay_type=pay_type,
            phone=g.user.phone, amount=price, sjamount=poundage, user_url=user_url
        )
        if result is False:
            return restful.params_error(message='支付失败')

        if pay_type == 0:
            order_pay_type = 1
            pay_type_str = 'alipay'
        else:
            order_pay_type = 2
            pay_type_str = 'wxpay'
        order_id_str = 'HM{}{}'.format(pay_type_str, trade_no)
        today = date.today()
        withdraw_order = WithdrawOrder(
            price=price, user_id=g.user.id, w_type=w_type,
            withdraw_date=today, income=poundage,
            pay_type=order_pay_type, trade_no=order_id_str
        )
        db.session.add(withdraw_order)
        api_util.user_record(user_id=g.user.id, r_label=10, r_type=2, r_state=2, num=poundage, r_wallet=10, status=0)
        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        return restful.params_error(message='网络错误，请重试！')


@bp.route('/scan_notify/')  # 回调成功接口
def scan_notify():
    username = request.args.get('username')
    amount = request.args.get('amount')
    order_id = request.args.get('order_id')
    user = User.query.filter_by(phone=username).first()
    message = '参数:username:{},amount:{},order_id:{}'.format(username, amount, order_id)
    if user is None:
        print('回调失败: 未找到用户' + message)
        return restful.params_error(message='未找到用户' + message)

    withdraw_order = WithdrawOrder.query.filter(
        WithdrawOrder.user_id == user.id, WithdrawOrder.trade_no == order_id,
        or_(WithdrawOrder.status == 0)
    ).first()
    if withdraw_order is None:
        print('回调失败: 未找到订单' + message)
        return restful.params_error(message='未找到订单' + message)
    withdraw_order.status = 1
    withdraw_order.update_time = datetime.now()
    print('回调成功接口 订单号:' + WithdrawOrder.trade_no)
    db.session.commit()
    return 'success'


@bp.route('/scan_back/')    # 失败退款接口
def scan_back():
    username = request.args.get('username')
    amount = request.args.get('amount')
    order_id = request.args.get('order_id')
    user = User.query.filter_by(phone=username).first()
    message = '参数:username:{},amount:{},order_id:{}'.format(username, amount, order_id)
    if user is None:
        print('回调失败: 未找到用户' + message)
        return restful.params_error(message='未找到用户' + message)
    withdraw_order = WithdrawOrder.query.filter(
        WithdrawOrder.user_id == user.id, WithdrawOrder.trade_no == order_id,
        or_(WithdrawOrder.status == 0, WithdrawOrder.status == 1)
    ).first()
    if withdraw_order is None:
        print('回调失败: 未找到订单' + message)
        return restful.params_error(message='未找到订单' + message)

    now = datetime.now()
    withdraw_order.status = 2
    withdraw_order.update_time = now

    user.income_s += withdraw_order.income
    api_util.user_record(user_id=user.id, r_label=10, r_type=3, r_state=1, num=withdraw_order.income, r_wallet=10, status=0)

    db.session.commit()
    print('失败退款接口 订单号:', WithdrawOrder.trade_no)
    return 'success'

